<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 400px;
            height: 100px;
            border: 1px solid black;
            position: relative;
            margin: 50px auto;
        }

        .box p {
            height: 20px;
            margin: 0;
            position: absolute;
            top: 40px;
            left: 0;
            background: pink;
            width: 10px;
        }
    </style>
</head>

<body>
    <div class="box">
        <p></p>
    </div>
</body>
<script>
    // 选择器
    var op = document.querySelector(".box p");
    // 用来保存计数器的返回值
    var t;
    // 步长
    var speed = 2;
    // 目标
    var target = 400;
    // 事件执行函数
    document.onclick = function () {
        // 开启之前先清除一个计时器
        clearInterval(t);
        // 设置计时器
        t = setInterval(function () {
            // 获取当前值
            var now = parseInt(getStyle(op, "width"))
            //    判断剩下的距离是否满足一步
            if (target - now < speed) {
                //    清除计时器
                clearInterval(t);
                //    进度强制设为宽度
                op.style.width = target + "px";
            } else {
                //    在当前距离之上再增加一步，再设置回去
                op.style.width = now + speed + "px"
            }
        }, 30)

    }


    function getStyle(ele, attr) {
        if (ele.currentStyle) {
            return ele.currentStyle[attr];
        } else {
            return getComputedStyle(ele)[attr]
        }
    }
</script>

</html>